// pages/details/details.js
import WxParse from '../../wxParse/wxParse.js';
import util from '../../utils/util.js';
const app = getApp();
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({

  /**
   * 页面的初始数据
   */
  data: {
    v:0,
    isShow: false,
    imgShow: false,
    hostUrl: app.globalData.hostUrl,
    showModel: true,
    showCeng: true,
    guigebackground:'',
    num:1,
    quantity:1,
    stock:0,
    id:'',
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    animationData: {},
    animationisno: false,
    guilist: {},
    arrId: [],
    arrName: [],
    textStates: ["view-btns-text-normal", "view-btns-text-select"],
    goods_spec: [],
    product_img:[],
    // 选项卡
    tabs: ["宝贝详情", "全部评价"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    hostUrl: app.globalData.hostUrl,

  },
  closeAllLayer: function () {
    this.setData({
      showModel: true,
      showCeng: true
    })
  },
  chooseModel: function () {
    // if (this.data.user['LevelId']==1) {
    //   wx.showToast({
    //     title: '请升级VIP,即可购买',
    //     icon: 'none'
    //   })
    //   return;
    // }
    this.setData({
      showCeng: false,
      showModel: false
    })
  },
// 选项卡事件
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
    that.setData({
      id: options.id,
    });
    // console.log(that.data.id)
    that.isshoucang(options.id);//检测商品是否收藏过
    that.getInfo(options);//读取详细
    that.add_foot();
    that.getUser();

  },
  getUser: function () {//读取会员
    var that = this;
    var userid = wx.getStorageSync('userId');
    wx.request({
      url: app.globalData.apiUrl + 'user/getUser',
      data: {
        // opt: 'getUser',
        userId: userid,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res, '用户信息')

          that.setData({
            user: res.data,
           

          })
      }

    })
    // console.log(that.data.canIUse)
  },
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },
  // 关闭弹窗图片
  shutDown: function () {
    this.setData({
      imgShow: false,
      isShow: false,
      v:1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  getInfo: function (options) {//读取详细
    var that = this;
    let guilists = that.data.guilist;
    wx.request({
      url: app.globalData.apiUrl +'Index/getProductInfo',
      data: {
        userId:wx.getStorageSync('userId'),
        // // opt: 'getProductInfo',
        id: that.data.id,//商品id
        // id: options,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res.data.product_img, '图片')
        // console.log(res.data.spec_goods_price,'规格与价格')
          // guilists.price = res.data.yuanPriceVip;//价格
          // guilists.store_count = res.data.Sales;//库存
          console.log(res.data)
          WxParse.wxParse('Content', 'html', res.data.Content, that, 5),
          that.setData({
            goodsList: res.data,
            product_img: res.data.product_img,
            goods_spec: res.data.guige,
            spec_goods_price: res.data.spec_goods_price,
            guilist: res.data.spec_goods_price[0],
            stock: res.data.spec_goods_price[0]['Inventory'],

            // minprice: (res.data.marketPrice - res.data.price).toFixed(2),
          })
          // console.log(that.data.goodsList,'基本信息')
          wx.setNavigationBarTitle({ title: res.data.Title });//顶部标题
          
        
        
      }
    })
  },
  ///添加足迹
  add_foot: function () {
    var that = this;
    wx.request({
      url: app.globalData.apiUrl + 'User/add_foot',
      data: {
        userId: wx.getStorageSync('userId'),
        goods_id: that.data.id,//商品id
        // id: 152,
      },

      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
      }
    })
  },
  //非冒泡事件选规格
  selectGuige(e) {
    // console.log(e)
    let that = this,
      // 获取第一个循环的index
      fuindex = e.currentTarget.dataset.fuindex,
  
      // 获取第二个循环的index
      chindex = e.currentTarget.dataset.chindex,
      // 获取当前点击的id
      selectId = e.currentTarget.dataset.id,
      // 获取当前点击的规格名称
      selectName = e.currentTarget.dataset.item,
      //  初始化arrId
      arrId = that.data.arrId,
      //  初始化arrName
      arrName = that.data.arrName,
      guilists = {},
      goods_spec = that.data.goods_spec;
    // console.log(goods_spec)
    // 通过循环来判断点击了哪一个规格，根据数据结构来；
    // goods_spec[fuindex]根据fuindex来判断点击了哪一种类型的规格
    for (let i = 0; i < goods_spec[fuindex]['spec_son'].length; i++) {
      // 当i等于当前点击的规格时，设置isClick=1
      if (i == chindex) {
        goods_spec[fuindex]['spec_son'][i].isClick = 1;
      }
      // 否则设置其他的isClick=0
      else {
        goods_spec[fuindex]['spec_son'][i].isClick = 0;
      }
    };
    // 把点击的规格名称和规格id存起来
    arrId[fuindex] = selectId;
    // console.log(arrId,'把点击的规格名称和规格id存起来')
    arrName[fuindex] = selectName;
    // console.log(arrName)
    // 拼接规格id，（后台返回的数据是这个）
    let selectGuigeId = arrId.join('_');
    // console.log(selectGuigeId)
    for (let i = 0; i < that.data.spec_goods_price.length; i++) {
      // 找对应的规格组合
      if (that.data.spec_goods_price[i].Key == selectGuigeId) {
        guilists = that.data.spec_goods_price[i];
       
      }
      
    }
    // console.log(guilists)
    that.setData({
      goods_spec: goods_spec,
      // arrId,
      guilist: guilists,
      selectGuigeName: arrName,
      stock: guilists['Inventory'],
    })
    // console.log(that.data.guilist)
  },
  cart:function(e){//加入购物车
    var that=this;
    var id = e.currentTarget.dataset.id;
    var userId = wx.getStorageSync('userId');
    let selectguigeid = that.data.arrId.join('_');//把逗号转换_
    if (userId != null && userId > 0 && userId != '') {
      for (let i = 0; i < that.data.spec_goods_price.length; i++) {
        if (that.data.spec_goods_price[i].Key == selectguigeid) {
          // wx.request({
          //   url: app.globalData.apiUrl + 'Car/getFreight',
          //   data: {
          //     // opt: 'addCart',
          //     product_id: that.data.id,
          //     Key: selectguigeid,
          //     num: that.data.quantity,

          //   },
          //   success: function (res) {
          //     if (res.data.status == 0) {
          //       wx.showToast({
          //         title: '该地区不配送',
          //       })
          //       return;
          //     }
          //   }
          // })
         
          that.addCart(id, userId, that.data.quantity, 1, that.data.arrId, selectguigeid);
        }else{
          // console.log(2222)
          wx.showToast({
            title: '请选择规格',
            icon:'success',
          })
        }
      } 
    }else{
      wx.showModal({
        title: '温馨提示',
        content: '请先登录后购买',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  book: function (e) {//立即购买
    //弹窗
    // if (this.data.v == 0) {
    //   this.setData({
    //     imgShow: true,
    //     isShow: true
    //   })
    //   return;
    // }
    var that = this;
    var id = e.currentTarget.dataset.id;
    let selectguigeid = that.data.arrId.join('_');//把逗号转换_
    // console.log(selectguigeid)
    // return ;
    var userId = wx.getStorageSync('userId');//用户id
    if (userId != null && userId > 0 && userId != '') {
      for (let i = 0; i < that.data.spec_goods_price.length; i++) {
        if (that.data.spec_goods_price[i].Key == selectguigeid) {
          var isxuanguige = 1;
          break;
        }else{
          var isxuanguige = 2;
        }
        // console.log(isxuanguige,'是否选规格')
      } 
      if (isxuanguige == 1) {

        that.addCart(id, userId, that.data.quantity, 2, that.data.arrId, selectguigeid, that.data.Category);
      } else {
        wx.showToast({
          title: '请选择规格',
          icon: 'success',
        })
        return;        
      }
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '请先登录后购买',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  addCart: function (id, userId, quantity, isChecked, arrId, arrName, Category) {//读取详细
    var that = this;
    wx.request({
      url: app.globalData.apiUrl+'Car/addCart',
      data: {
        // opt: 'addCart',
        id: id,
        userId: userId,
        quantity: quantity,
        isChecked: isChecked,
        // arrId: arrId,
        arrName: arrName,
        // Category: Category,
        // unit: unit,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data != null) {
          if (res.data.status==0&&isChecked==1){
            // if (res.data.is_have=="no"){
            //   wx.showModal({
            //     title: '提示',
            //     content: '此地区不发货',
            //     success(res) {
            //       if (res.confirm) {
            //         wx.navigateTo({
            //           url: '../personal/address/addRess/addRess',
            //         })
            //       } else if (res.cancel) {
            //         console.log('用户点击取消')
            //       }
            //     }
            //   })
            //   return;   
            // }
            if (res.data.is_not =="no" ) {
              wx.showToast({
                title: '有其它地区商品',
                icon: 'success',
                duration: 2000
              })
              return; 
            }
            wx.showToast({
              title: '加入成功',
              icon: 'success',
              duration: 2000
            })  
          } else if (res.data.status == 0 && isChecked == 2){
            // if (res.data.is_have=="no"){
            //   wx.showModal({
            //     title: '提示',
            //     content: '此地区不发货',
            //     success(res) {
            //       if (res.confirm) {
            //         wx.navigateTo({
            //           url: '../personal/address/address',
            //         })
            //       } else if (res.cancel) {
            //         console.log('用户点击取消')
            //       }
            //     }
            //   })
            //   return ; 
            // }
            // console.log(res)
            var Count = res.data.Count;
            var Key = res.data.Key;
            var ProductId = res.data.ProductId;
            var Type = '立即购买';
            var Category=that.data.Category;
            wx.navigateTo({
              url: '/pages/con_order/con_order?Count=' + Count + '&Key=' + Key + '&ProductId=' + ProductId + '&Type=' + Type,
            })
          }else{
            wx.showToast({
              title: '失败',
              icon: 'error',
              duration: 2000
            })  
          }
        }
      }
    })
  },
 
  jian: function (e) {//减
    var that = this;
    if (that.data.quantity>1){
      that.setData({
        quantity: that.data.quantity-1,
      })
    }else{
      wx.showToast({
        title: '数量不能为0',
        icon: 'error',
        duration: 2000
      })  
    }
  },
  jia: function (e) {//加
    var that = this;
    // that.setData({
    //   stock:that.data.stock-1,
    // })
    // console.log(that.data.stock)
    // console.log(that.data.quantity)
    if (that.data.quantity < that.data.stock) {
      that.setData({
        quantity: that.data.quantity + 1,
      })
    }else{
      wx.showToast({
        title: '库存不足',
        icon: 'error',
        duration: 2000
      })  
    }
  },
  //检测店铺是否收藏
  isshoucang: function (productid) {
    var that = this;
    wx.request({
      url: app.globalData.apiUrl + 'Shop/isshoucang',
      data: {
        userId: wx.getStorageSync('userId'),
        productid: productid,
        shoucang_type: 'product',
      },
      success: function (res) {
        if (res.data.status == 0) {
          that.setData({
            hv: false
          })
        } else {
          that.setData({
            hv: true
          })
        }
        console.log(that.data.hv, '是否收藏')
      },
    })
  },
  //收藏
  shoucang: function (e) {
    var that = this;
   
      
      wx.request({
        url: app.globalData.apiUrl + 'Index/collect',
        data: {
          // opt: 'getBanner',
          // id: that.data.id,//
          userId: wx.getStorageSync('userId'),
          id: that.data.id,
          type: 'product',

        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res)
          if (res.data != null) {
            wx.showToast({
              title: res.data.message,
              icon: 'success',
            })
            that.setData({
              hv:true
            })
          }
        }
      })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }

})